package com.ryder.ryderschool.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryder.ryderschool.entity.User;
import com.ryder.ryderschool.mapper.UserMapper;
import com.ryder.ryderschool.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public String login(String username, String password) {
        User user = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!user.getPassword().equals(DigestUtil.md5Hex(password))) {
            throw new RuntimeException("密码错误");
        }
        StpUtil.login(user.getId());
        return StpUtil.getTokenValue();
    }

    @Override
    public void register(User user) {
        // 检查用户名是否已存在
        if (lambdaQuery().eq(User::getUsername, user.getUsername()).count() > 0) {
            throw new RuntimeException("用户名已存在");
        }
        // 加密密码
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        save(user);
    }

    @Override
    public User getCurrentUser() {
        Integer userId = StpUtil.getLoginIdAsInt();
        return getById(userId);
    }
} 